#include <QtGui>
#include <QtXml>
#include <iostream>

#include "domparser.h"

DomParser::DomParser(QTreeWidget *tree)
{
	treeWidget = tree;
}

bool DomParser::readFile(const QString &fileName)
{
	QFile file(fileName);
	if (!file.open(QFile::ReadOnly | QFile::Text)) {
		std::cerr << "Error: Cannot read file " << qPrintable(fileName)
			<< ": " << qPrintable(file.errorString())
			<< std::endl;
		return false;
	}

	QString errorStr;
	int errorLine;
	int errorColumn;

	QDomDocument doc;
	if (!doc.setContent(&file, false, &errorStr, &errorLine, &errorColumn)) {
		std::cerr << "Error: Parse error at line " << errorLine << ", "
			<< "column " << errorColumn << ": "
			<< qPrintable(errorStr) << std::endl;
		return false;
	}

	QDomElement root = doc.documentElement();
	if (root.tagName() != "bookindex") {
		std::cerr << "Error: Not a bookindex file" << std::endl;
		return false;
	}

	parseBookindexElement(root);
	return true;
}

void DomParser::parseBookindexElement(const QDomElement &element)
{
	QDomNode child = element.firstChild();
	while (!child.isNull()) {
		if (child.toElement().tagName() == "entry")
			parseEntryElement(child.toElement(), treeWidget->invisibleRootItem());
		child = child.nextSibling();
	}
}

void DomParser::parseEntryElement(const QDomElement &element,
	QTreeWidgetItem *parent)
{
	QTreeWidgetItem *item = new QTreeWidgetItem(parent);
	item->setText(0, element.attribute("term"));

	QDomNode child = element.firstChild();
	while (!child.isNull()) {
		if (child.toElement().tagName() == "entry") {
			parseEntryElement(child.toElement(), item);
		}
		else if (child.toElement().tagName() == "page") {
			parsePageElement(child.toElement(), item);
		}
		child = child.nextSibling();
	}
}

void DomParser::parsePageElement(const QDomElement &element,
	QTreeWidgetItem *parent)
{
	QString page = element.text();
	QString allPages = parent->text(1);
	if (!allPages.isEmpty())
		allPages += ", ";
	allPages += page;
	parent->setText(1, allPages);
}
